package com.guli.product.app;

import java.util.Arrays;
import java.util.Map;


import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.guli.common.utils.PageUtils;
import com.guli.common.utils.R;
import com.guli.product.entity.AttrAttrgroupRelationEntity;
import com.guli.product.service.AttrAttrgroupRelationService;
import com.guli.product.vo.AttrVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import com.guli.product.entity.AttrEntity;
import com.guli.product.service.AttrService;


/**
 * 商品属性
 * @author zzb
 * @email 1626131069@qq.com
 * @date 2023-10-21 10:18:56
 */
@RestController
@RequestMapping("product/attr")
public class AttrController {
    @Autowired
    private AttrService attrService;
    @Autowired
    private AttrAttrgroupRelationService attrAttrgroupRelationService;

    /**
     * 根据type字段显示规格参数或销售属性
     * @param type
     * @param catId
     * @param params
     * @return
     */
    @RequestMapping("{type}/list/{catId}")
    public R list(@PathVariable String type, @PathVariable Long catId,
                  @RequestParam Map<String, Object> params) {
        PageUtils page = attrService.queryPage(type, catId, params);
        return R.ok().put("page", page);
    }

    /**
     * 根据attrId显示该属性
     * @param attrId
     * @return
     */
    @RequestMapping("/info/{attrId}")
    public R info(@PathVariable("attrId") Long attrId) {
        AttrVo attrVo = attrService.getInfoById(attrId);
        return R.ok().put("attr", attrVo);
    }

    /**
     * 保存新增属性和该属性与属性分组关联信息
     * @param attr
     * @return
     */
    @RequestMapping("/save")
    public R save(@RequestBody AttrVo attr) {
        attrService.saveAndAttrGroup(attr);
        return R.ok();
    }

    /**
     * 修改该属性信息
     * @param attrVo
     * @return
     */
    @PostMapping("/update")
    public R update(@RequestBody AttrVo attrVo) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attrVo,attrEntity);
        attrService.updateById(attrEntity);
        Long attrGroupId = attrVo.getAttrGroupId();
        if (attrGroupId != null){
            AttrAttrgroupRelationEntity attrgroupRelation = new AttrAttrgroupRelationEntity();
            attrgroupRelation.setAttrGroupId(attrGroupId);
            attrAttrgroupRelationService.update(attrgroupRelation,new UpdateWrapper<AttrAttrgroupRelationEntity>()
                    .eq("attr_id",attrVo.getAttrId()));
        }
        return R.ok();
    }

    /**
     * 删除该属性
     * @param attrIds
     * @return
     */
    @RequestMapping("/delete")
    public R delete(@RequestBody Long[] attrIds) {
        attrService.removeByIds(Arrays.asList(attrIds));
        return R.ok();
    }

}
